package com.cdks.wuxiu.api.service.mysql;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdks.wuxiu.api.component.constant.Constant;
import com.cdks.wuxiu.api.mapper.UserSaveInfoMapper;
import com.cdks.wuxiu.entity.mysql.UserSaveInfo;

import org.springframework.stereotype.Service;

/**
 * 用户收藏 服务实现类
 */
@Service
public class UserSaveInfoServiceImpl extends ServiceImpl<UserSaveInfoMapper, UserSaveInfo> implements UserSaveInfoService {

    private int saveData(long userId, long destId, int type, int status) {
        QueryWrapper<UserSaveInfo> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(UserSaveInfo::getUserId, userId)
                        .eq(UserSaveInfo::getDestId, destId)
                        .eq(UserSaveInfo::getType, type);

        UserSaveInfo saveInfo  = baseMapper.selectOne(wrapper);
        if (saveInfo == null)
        {
            saveInfo  = new UserSaveInfo();

            saveInfo.setUserId(userId);
            saveInfo.setDestId(destId);
            saveInfo.setStatus(status);
            saveInfo.setType(type);

            int ret  = baseMapper.insert(saveInfo);
            if (ret > 0)
            {
                return 0;
            }
        }
        else
        {
            if (saveInfo.getStatus() == status)
            {
                return 1;
            }

            saveInfo.setStatus(status);
            int ret  = baseMapper.updateById(saveInfo);
            if (ret == 1)
            {
                return 0;
            }
        }

        return -1;
    }

    @Override
    public int collect(long userId, long destId, int type) {
        int ret  = saveData(userId, destId, type, Constant.USER_ACTION_COLLECT);
        if (ret < 0)
        {
            return -1;
        }

        if (ret == 1)
        {
            return 1;
        }

        return 0;
    }

    @Override
    public int cancel(long userId, long destId, int type) {
        int ret  = saveData(userId, destId, type, Constant.USER_ACTION_CANCEL);
        if (ret < 0)
        {
            return -1;
        }

        if (ret == 1)
        {
            return 1;
        }

        return 0;
    }

    @Override
    public int getSaveStatus(long userId, long destId, int type) {
        QueryWrapper<UserSaveInfo> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(UserSaveInfo::getDestId, destId)
                        .eq(UserSaveInfo::getUserId, userId)
                        .eq(UserSaveInfo::getType, type);

        UserSaveInfo saveInfo  = baseMapper.selectOne(wrapper);
        if (saveInfo == null)
        {
            return 0;
        }

        return saveInfo.getStatus();
    }
}
